const headers = new Headers({
  "Access-Control-Allow-Origin": "*",
  Accept: "*",
  "Content-Type": "application/json",
});

function get(url) {
  headers.set("Content-Type", "application/json");
  headers.set("authorization", sessionStorage.getItem("token"));
  return fetch(url, {
    method: "GET",
    mode: "cors",
    headers: headers,
  })
    .then((response) => {
      return handleResponse(url, response);
    })
    .catch((err) => {
      console.error(`Request failed. Url = ${url} . Message = ${err}`);
      return { error: { message: "Request failed." } };
    });
}

function post(url, data) {
  headers.set("Content-Type", "application/json");
  headers.set("authorization", sessionStorage.getItem("token"));
  return fetch(url, {
    method: "POST",
    mode: "cors",
    headers: headers,
    body: JSON.stringify(data),
  })
    .then((response) => {
      return handleResponse(url, response);
    })
    .catch((err) => {
      console.error(
        `Request failed. Url = ${url} . Message = ${err.statusText}`
      );
      return { error: { message: "Request failed." } };
    });
}

export function multipartPost(url, data) {
  headers.set("authorization", sessionStorage.getItem("token"));
  // headers.set(
  //   "content-type",
  //   "multipart/form-data;boundary=---011000010111000001101001"
  // );
  headers.delete("Content-Type");
  console.log("aaa", data);
  const option = {
    method: "POST",
    mode: "cors",
    headers: headers,
  };
  option.body = data;
  return fetch(url, option)
    .then((response) => {
      return handleResponse(url, response);
    })
    .catch((err) => {
      console.error(
        `Request failed. Url = ${url} . Message = ${err.statusText}`
      );
      return { error: { message: "Request failed." } };
    });
}

function put(url, data) {
  headers.set("authorization", sessionStorage.getItem("token"));
  return fetch(url, {
    method: "PUT",
    headers: headers,
    body: JSON.stringify(data),
  })
    .then((response) => {
      return handleResponse(url, response);
    })
    .catch((err) => {
      console.error(`Request failed. Url = ${url} . Message = ${err}`);
      return { error: { message: "Request failed." } };
    });
}

function handleResponse(url, response) {
  if (response.status < 500) {
    return response.json();
  } else {
    console.error(
      `Request failed. Url = ${url} . Message = ${response.statusText}`
    );
    return { error: { message: "Request failed due to server error " } };
  }
}

export { get, post, put };
